package com.arun.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.arun.entity.Data;
import com.arun.service.YMDDaoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.arun.dao.ssm.YMDDao;
import com.arun.dto.C7mtpDTO;
import com.arun.entity.C7MTP;
import com.arun.entity.Result;
import com.arun.mappers.CommonMapper;
import com.arun.service.C7MPTService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class YMDController {
	@Resource(name = "httpClientTemplate")
	private RestTemplate httpClientTemplate;
	@Autowired
	private CommonMapper commonMapper;

	@Autowired
	private C7MPTService c7mtpService;
	@Autowired
	private YMDDaoService ymdDaoService;

	private Logger logger = LoggerFactory.getLogger(YMDController.class);

	@RequestMapping(value = "GetYMDCheckSN.action")
	@ResponseBody
	public String getYMDCheckSN(@RequestParam(required = true, defaultValue = "7B16201500366") String CSN) {
		String p = "{\"sns\":[\"" + CSN + "\"]}";
		String url = "https://console.ehuandian.net/ecadmin/batteryStore/juedgeBatteryStore";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> httpEntity = new HttpEntity<>(p, headers);
		// ResponseEntity<String> entity = httpClientTemplate.getForEntity(url,
		// String.class);
		ResponseEntity<String> responseEntity = httpClientTemplate.exchange(url, HttpMethod.GET, httpEntity,
				String.class);
		String body = responseEntity.getBody();
		return body;
	}

	@PostMapping("/binding")
	@ResponseBody
	public Object binding(@RequestBody Map<String, Object> params, HttpSession session) {
		HashMap<Object, Object> map = new HashMap<>();
		String sn = (String) params.get("sn");
		String mac = (String) params.get("mcu");

		//System.out.println(sn + " " + mac);
		C7MTP c7mtp = new C7MTP();
		C7mtpDTO c7Dto = new C7mtpDTO();
		// C7MTP resC7mtp = new C7MTP();
		try {

			if (sn.length() > 10 && mac.length() > 15) {
				c7Dto.setMac(mac);
				c7Dto.setSn(sn);
				
				c7mtp.setSn(sn);
				c7mtp.setMac(mac);
				c7mtp.setVersion(1);
				Result result = c7mtpService.uploadSNAndMAC(c7Dto);

				if("200".equals(result.getCode())) {
					c7mtp.setIs_upload("Y");
					map.put("result", sn + "  " + mac + " 绑定成功。");
					map.put("binded", "1");
				}else {
					c7mtp.setIs_upload("N");
					map.put("result", sn + "  " + mac + " 上传易马达服务器异常:" + result.getError());
					map.put("binded", "0");
				}
				c7mtp.setCode(result.getCode());
				c7mtp.setError(result.getError());
				int i = c7mtpService.saveC7MPT(c7mtp);
				//map.put("id", i);
			}else {
				map.put("result", sn + "  " + mac + " SN或者MAC不符合长度:");
				map.put("binded", "0");
			}

		} catch (Exception e) {
			logger.error("上传易马达服务器异常",e);
			map.put("result", sn + "  " + mac + "上传易马达服务器异常:" + e.getMessage());
			map.put("binded", "0");
		}
		// logger.info("login password:{}",user.getPassword());


		return map;
	}

	@RequestMapping(value = "PostYMDC7MTP.action")
	@ResponseBody
	public String BindC7MTP(@RequestParam(required = true, defaultValue = "7B16201500366") String SN, String MAC) {
		/**
		 * String p = "{\"sns\":[\"" + SN + "\"]}"; String url =
		 * "https://console.ehuandian.net/ecadmin/batteryStore/juedgeBatteryStore";
		 * HttpHeaders headers = new HttpHeaders();
		 * headers.setContentType(MediaType.APPLICATION_JSON);
		 * headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		 * HttpEntity<String> httpEntity = new HttpEntity<>(p, headers); //
		 * ResponseEntity<String> entity = httpClientTemplate.getForEntity(url,
		 * String.class); ResponseEntity<String> responseEntity =
		 * httpClientTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
		 * String body = responseEntity.getBody();
		 **/
		System.out.println(SN + " " + MAC);
		C7MTP c7mtp = new C7MTP();
		c7mtp.setSn(SN);
		c7mtp.setMac(MAC);
		//c7mtpService.uploadSNAndMAC(c7Dto);
		c7mtpService.saveC7MPT(c7mtp);
		System.out.println("c7mtp's id " + c7mtp.getId());
		return "HELLO";
	}
	
	/**
	 * 
	 * 01;工号;序号;工序名称;资源名称;
	 * 04;工号;序号;工序名称;资源名称;测试开始时间;检测项1:结果值1,检测项2:结果值2;
	 * 05;工号;序号;BID;工序名称;资源名称; 测试结果;不良现象;
	 * 结果判断存储过程 P_AgeTest DB.AgeTest.SaveAgeFlow("40", txtPSN.Text, "NG"); (流程号,SN,测试结果OK/NG)
	 * @param s
	 * @return
	 */
	@RequestMapping(value = "AgeTest.action")
	@ResponseBody
	public Result upLoadAgeTest(@RequestBody String s) {
		Result result = new Result();
		String[] arrStr = s.split(";");
    	for(int i=0;i<arrStr.length;i++) {
    		System.out.println(arrStr[i]);
    	}

		result.setCode("OK");
		result.setError("OK Message");
		return result;
	}

	/**
	 * 上传德合盛分容设备数据
	 *
	 * @return
	 */
	@RequestMapping(value = "DHSAgeTest.action")
	@ResponseBody
	public Result upLoadDHSAgeTest(@RequestBody Data data) {
		Result result = new Result();
		int updates = ymdDaoService.saveCUXDHSBatteryINFOFromData(data);
		//System.out.println("updates = " + updates);
		//System.out.println("data = " + data);
		if(updates>0){
			result.setCode("OK");
			result.setError("数据上传成功");
		}else {
			result.setCode("NG");
			result.setError("数据上传失败");
		}

		return result;
	}

	@RequestMapping(value="checkSN.action")
	@ResponseBody
	public Result CheckSNFlow(String DeviceNo,String Barcode ) {
		Result result = new Result();
		try {
			
			Map<String,Object> mParam = new HashMap<String, Object>(); 
			mParam.put("DeviceNo", DeviceNo);
			mParam.put("Barcode", Barcode);
			c7mtpService.checkSNFlow(mParam); 
			String resCode =  Integer.parseInt(mParam.get("ResultCode").toString() ) >= 0 ? "true" : "false";
			String resMsg = mParam.get("ResultMsg").toString();
			result.setCode(resCode);
			result.setError(resMsg); 
			
		}catch (Exception e) {
			result.setCode("NG");
			result.setError(e.getMessage()); 
		}
		return result;
	}
	
	@GetMapping("/test/getall")
	@ResponseBody
	public List<C7MTP> selectAll() {
	    List<C7MTP> list = c7mtpService.queryAll();

		return list;
	}
	
	@GetMapping("/test/select")
	@ResponseBody
	public Object select() {
		List<LinkedHashMap<String, Object>> mapList = commonMapper.getPublicItems(
				"SELECT mbo_Barcode,mbo_BillNo FROM MES_BarcodeOrder where mbo_Barcode ='191214020102' ");

		return mapList;
	}

	@CrossOrigin // 跨域
	@GetMapping("/test/cros")
	@ResponseBody
	public String crosTest(HttpServletResponse response) {
	   
		return "Hello,@CrossOrigin";
	}
	
}
